#!/bin/sh

echo "------------------------开始进行备份 开始时间是`date '+%Y-%m-%d %H:%M:%S'`------------------------"

# 备份文件名称定义
BACKUP_FILE_NAME=mariadb_backup

BACKUP_DIR=$(
    cd "$(dirname "$0")"
    pwd
)
# 进入脚本所在目录，即备份的存储目录
cd $BACKUP_DIR

echo "开始备份数据库";

echo "进行导出数据库数据为sql文件"
docker exec mariadb sh -c 'exec mysqldump --all-databases -uroot -p"Hzsun@310012" ' > $BACKUP_FILE_NAME.sql;

echo "压缩sql文件"
tar -zcvf ${BACKUP_FILE_NAME}_$(date "+%Y%m%d%H%M").tar.gz $BACKUP_FILE_NAME.sql

# 删除原文件
rm -rf $BACKUP_FILE_NAME.sql

echo "删除多余备份文件"

# 保留的备份文件的最大个数
backup_number=3

success=0
while (success=0)
do
delfile=`ls -1 -crt *.tar.gz 2>/dev/null | head -1`
count=`ls -l -crt *.tar.gz | awk '{print $9 }' | wc -l`
if [ $count -gt $backup_number ]; then
   rm $delfile
   echo "删除最早生成的备份文件: $delfile"
else
   success=1
   break;
fi
done

# 删除 3 天前的备份文件
find $BACKUP_DIR -name $BACKUP_FILE_NAME"*.tar.gz" -type f -mtime +3 -exec rm -rf {} \;

echo "------------------------备份完成 结束时间是`date '+%Y-%m-%d %H:%M:%S'`------------------------"
